<template>
    <van-address-edit 
        show-delete
        show-set-default
        :area-list="areaList"
        :area-columns-placeholder="['请选择', '请选择', '请选择']"
        :address-info="address"
        @save="save"
        @delete="del"
    />
</template>

<script setup>
    //引入地区数据
    import { areaList } from '@vant/area-data'

    //获取个人资料
    const{proxy} = getCurrentInstance()

    let business = proxy.$business

    //接受专递过来的id router route
    let id = proxy.$route.query.id ? proxy.$route.query.id : 0

    let address = ref({
        name: business.value.nickname,
        tel: business.value.mobile,
        areaCode: business.value.district || business.value.city || business.value.province,
    })

    //生命周期钩子函数
    onMounted(() => info)
    const save = async (values) => {
        //组装数据
        var params = {
            busid: business.value.id,
            consignee: values.name,
            code: values.areaCode,
            address: values.addressDetail,
            mobile: values.tel,
            status: values.isDefault ? 1 : 0,
            id
        }

        var result = await proxy.$POST({url:'/address/edit',params})

        if(result.code == 0)
        {
            return proxy.$fail(result.msg)
        }

        proxy.$success({
            message:result.msg,
            onClose: () => proxy.$router.go(-1)
        })
    }

    //删除收货地址
    const del = async (values) => {
        //弹出确认对话框
        var result = await proxy.$confirm({
            title:'删除提醒',
            message:'是否删除该地址',
        }).then(async() => {
            //组装数据
            var params = {
                busid: business.value.id,
                id
            }

            var result = await proxy.$POST({url:'/address/del',params})

            if(result.code == 0) return proxy.$fail(result.msg)

            proxy.$success({
                message:result.msg,
                onClose: () => proxy.$router.go(-1)//回到上一个界面
            })
        }).catch((err) => {})
    }

    //获取地址
    const info = async() => {
        //组装数据
        var params = {
            busid: business.value.id,
            id
        }

        var result = await proxy.$POST({url:'/address/info',params})

        if(result.code == 0)
        {
            proxy.$fail({
                message:result.msg,
                onClose: () => proxy.$router.go(-1)
            })
            return false
        }

        let areaCode = result.data.district || result.data.city || result.data.province

        address.value = {
            name:result.data.consignee,
            tel:result.data.mobile,
            addressDatail: result.data.address,
            areaCode:areaCode,
            isDefault: result.data.status ==  '1' ? true : false
        }
    }
</script>